package com.appcheck.recording.test;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.IntentFilter;
import android.view.View;

import com.appcheck.recording.BroadcastReceiverWrapper;
import com.appcheck.recording.ListenerManager;
import com.appcheck.recording.WidgetHelper;
import com.appcheck.recording.utils.DisplaySizeManager;
import com.appcheck.recording.utils.Logger;
import com.robotium.solo.Solo;

public class Recording {
	private Solo solo;
	
	private static String IntentName = "AddMsgToQueue";
	
	@SuppressWarnings("rawtypes")
	private BlockingQueue bq;
	
	public Recording(){
		this.bq = new LinkedBlockingQueue();
		Logger.initLogger("Demo Recording", true);
	}
	
	public void registerBroadcastReceiver(Instrumentation instrumentation){
		instrumentation.getTargetContext().registerReceiver(
				new BroadcastReceiverWrapper(this), 
				new IntentFilter(IntentName)
		);
	}
	
	public void addMsgToQueue(int message){
		try{
			Logger.INFO(new StringBuilder("Adding msg to queue: ").append(message).toString());
			this.bq.put(Integer.valueOf(message));
			return;
		}
		catch (InterruptedException localInterruptedException){
			Logger.ERROR("Blocking queue interrupted durring put msg", localInterruptedException);
		}
	}
	
	public void mainLoop(Instrumentation instrumentation, Activity activity){
		this.solo = new Solo(instrumentation, activity);
	    int index;
	    WidgetHelper.setSolo(solo);
	    DisplaySizeManager.getDisplaySize(activity);
	    ListenerManager.getListenerManager().setInstrumentation(instrumentation);
	    
	    for (;;){
	    	index = -1;
	    	try{
	    		index = ((Integer)this.bq.take()).intValue();
	    		Logger.INFO("the index of the blockedQueue is " + index);
	    	}catch (InterruptedException localInterruptedException){
	    		Logger.ERROR("Blocking queue interrupted during take msg", localInterruptedException);
	    	}
	    	switch (index){
	    	case 1: 
	    		this.solo.waitForView(View.class);
	    		ListenerManager.getListenerManager().init();
	    		break;
		    case 2: 
		    	this.solo.waitForDialogToOpen(0);
		    	ListenerManager.getListenerManager().init();
		    	break;
		    case 3: 
		    	break;
		    case 0: 
		    	return;
	      }
	    }
	}
}
